# -*- coding：utf-8 -*-
"""
@Time:2024-10-097:44
@Auth:泛彼泊舟
@File:assert_util.py
@IDE:PyCharm
@模块功能：专门解决断言的工具类
"""
import copy

import pymysql


class AssertUtil:

    # 连接数据库
    def conn_database(self):
        self.conn = pymysql.connect(
            user="sdm723416659",
            password="Msjy123456",
            host="sdm723416659.my3w.com",
            database="sdm723416659_db",
            port=3306
        )
        return self.conn

    # 执行SQL
    def execute_sql(self,sql):
        # 创建数据库连接
        conn = self.conn_database()
        # 创建游标
        cs = conn.cursor()
        # 执行sql
        cs.execute(sql)
        # 取值
        value = cs.fetchone()
        # 关闭资源
        cs.close()
        conn.close()
        # 返回值
        return value




    def assert_all_case(self,res, assert_type, value):
        # 1、深拷贝一个res
        new_res = copy.deepcopy(res)
        # 2.把json()方法改成json属性
        try:
            new_res.json = new_res.json()
        except Exception:
            new_res.json = {"msg": "response not json data"}
        # 3.循环判断断言
        for msg,yq_and_sj_data in value.items():
            sj, yq = yq_and_sj_data[0], yq_and_sj_data[1]
            # 根据属性获取到属性的值
            try:
                sj_value = getattr(new_res, sj)
                print(assert_type, msg, yq, sj_value)
            except Exception:
                sj_value = sj

            # 判断断言
            match assert_type:
                case "equals":
                    assert yq == sj_value, msg
                case "contains":
                   assert yq in sj_value, msg
                case "db_equals":
                    yq_value = self.execute_sql(yq)
                    assert yq_value[0] == sj_value, msg
                case "db_contains":
                    yq_value = self.execute_sql(yq)
                    assert yq_value[0] in sj_value, msg

